<template>
  <view class="sv-danmaku-item" :style="[{ '--track-width': trackWidth }, item.style]" @click="onDanmaku(item)">
    <image v-if="item.img" :src="item.img" class="prefix-img"></image>
    {{ item.text }}
  </view>
</template>

<script setup>
import { computed, onMounted } from 'vue'

const props = defineProps({
  // 每条独立的弹幕轨道
  item: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['updateAalive'])

/**
 * trackWidth：轨道基础宽度 (弹幕容器宽度px)
 * 最终弹幕滚动长度 = 轨道基础宽度 + 弹幕自身100%长度 + 预留距离(可选)
 * 即：from (trackWidth) to (-100% - 预留距离(可选))
 */
const trackWidth = computed(() => {
  return props.item.danmakuContainer?.width + 'px' || '0px'
})

/**
 * 弹幕的生命计时
 */
const living = (item) => {
  const lifeTimer = setTimeout(() => {
    item.alive = false
    // console.log('==== 释放 ====', item)
    // 通知父组件，该弹幕已经释放
    emit('updateAalive', item)
    clearTimeout(lifeTimer)
  }, item.time * 1000)
}

const onDanmaku = (e) => {
  uni.$emit('e-danmaku-click', e)
}

onMounted(() => {
  living(props.item)
})
</script>

<style lang="scss">
.sv-danmaku-item {
  --track-width: 0px;

  padding: 8rpx 16rpx;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 24rpx;
  white-space: nowrap;

  position: absolute;
  // transform: translateX(100%);
  animation: danmaku-running linear;
  display: flex;
  align-items: center;

  .prefix-img {
    width: 40rpx;
    height: 40rpx;
    margin-right: 8rpx;
    border-radius: 35%;
  }
}

@keyframes danmaku-running {
  0% {
    transform: translateX(var(--track-width));
  }

  100% {
    transform: translateX(calc(-100% - 40px));
  }
}
</style>